package com.rbcs.repay.webapp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.criterion.MatchMode;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;

import com.rbcs.borrow.model.Borrow;
import com.rbcs.flow.FlowConstants;
import com.rbcs.repay.RePayConstants;
import com.rbcs.repay.model.RePay;
import com.rbcs.repay.service.RePayManager;
import com.systop.common.modules.dept.model.Dept;
import com.systop.common.modules.security.user.UserUtil;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.ApplicationException;
import com.systop.core.dao.support.Page;
import com.systop.core.util.DateUtil;
import com.systop.core.util.PageUtil;
import com.systop.core.webapp.struts2.action.JsonCrudAction;

/**
 * 借款还款申请管理Action
 * @author ShangHua
 *
 */
@SuppressWarnings({"serial", "unchecked", "rawtypes"})
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class RePayAction extends JsonCrudAction<RePay, RePayManager> {

	//JSON数据
	private Map<String, String> jsonResult;
	
	//开始时间
	private Date startDate;

	//结束时间
	private Date endDate;
	
	/**
	 * 查询当前登录用户创建的还款申请单
	 */
	public String index(){
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		StringBuffer hql = new StringBuffer("from RePay p where 1 = 1 ");
		List args = new ArrayList();
		User user = UserUtil.getPrincipal(getRequest());
		if (user != null) {
      hql.append("and p.rePayer.id = ? ");
      args.add(user.getId());
		}	
		commonCondition(hql, args);
		hql.append("order by p.createDate desc");
		page = getManager().pageQuery(page, hql.toString(), args.toArray());
		restorePageData(page);
		
		return INDEX;
	}
	
	/**
	 * 出纳查询的还款申请单，用于审核还款单
	 * @return
	 */
	public String cashierIndex(){
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		StringBuffer hql = new StringBuffer("from RePay p where 1 = 1 ");
		List args = new ArrayList();
    hql.append("and p.audStatus != ? ");
    args.add(FlowConstants.AUDIT_UNSEND);
		commonCondition(hql, args);
		hql.append("order by p.createDate desc");
		page = getManager().pageQuery(page, hql.toString(), args.toArray());
		restorePageData(page);
		
		return "cashierIndex";
	}
	
	/**
	 * 公共的查询条件
	 * @param hql
	 * @param args
	 */
	private void commonCondition(StringBuffer hql, List<Object> args) {
		if (StringUtils.isNotBlank(getModel().getAudStatus())) {
      hql.append("and p.audStatus = ? ");
      args.add(getModel().getAudStatus());
		}
		if (StringUtils.isNotBlank(getModel().getSingleNo())) {
			hql.append("and p.singleNo like ? ");	
			args.add(MatchMode.ANYWHERE.toMatchString(getModel().getSingleNo()));
		}	
		if (startDate != null) {
			hql.append("and b.createDate >= ? ");
			args.add(startDate);
		}
		if (endDate != null) {
			hql.append("and b.createDate <= ? ");
			args.add(endDate);
		}
	}
	
	/**
	 * 新建还款单信息
	 */
	@Override
	public String edit(){
		if (getModel().getId() == null) {
		  getModel().setCreateDate(new Date());
			getModel().setDept(getLoginUserDept());
			String singleNo = DateUtil.getDateTime("yyyyMMddHHmmss", new Date());
			getModel().setSingleNo(RePayConstants.REPAY_SINGLE_PREFIX + singleNo);
		}
		return super.edit();
	}
	
	/**
	 * 保存还款单信息
	 */
	@Override
	public String save() {
		User user = UserUtil.getPrincipal(getRequest());
		if (user != null) {
			getModel().setRePayer(user);
		} else {
			this.addActionMessage("当前登录用户信息不存在，请您重新登录系统！");
			return INPUT;
		}
    try {
  		String borrowId = getRequest().getParameter("borrowId");
  		if (StringUtils.isNotBlank(borrowId)) {
  			Borrow borrow = getManager().getDao().get(Borrow.class, Integer.valueOf(borrowId));
      	getModel().setBorrow(borrow);
      	if (getModel().getId() == null) {
      		getModel().setCreateDate(new Date());
      		getModel().setDept(getLoginUserDept());
      		getModel().setAudStatus(FlowConstants.AUDIT_UNSEND);
      		getModel().setType(RePayConstants.REPAY_TYPE_NORMAL);
      	}
  		}
  		getManager().save(getModel());
      return SUCCESS;
    } catch (Exception e) {
      addActionError(e.getMessage());
      return INPUT;
    }
	}
	
	/**
	 * 发送还款申请到流程表【AJAX调用】
	 * 
	 * @return
	 */
	public String sendApply() {
		jsonResult = Collections.synchronizedMap(new HashMap<String, String>());
		String rePayId = getRequest().getParameter("rePayId");
		if (StringUtils.isNotBlank(rePayId)) {
			RePay rePay = getManager().get(Integer.valueOf(rePayId));
			try{
				rePay.setAudStatus(FlowConstants.AUDIT_PENDING);
				getManager().save(rePay);	
				jsonResult.put("result", "success");
			  } catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "jsonResult";	
	}
	
	/**
	 * 还款单审批
	 * @return
	 */
	public String rePayAudit() {
		if (getModel().getId() == null) {
		  getModel().setAudDate(new Date());
		}
		return "rePayAudit";
	}
	
	/**
	 * 保存还款申请审批
	 * @return
	 */
	@Transactional	
	public String saveRePayAudit() {
		if (getModel() != null && getModel().getId() != null) {
			getModel().setAuditor(UserUtil.getLoginUser(getRequest()));
			getManager().save(getModel());
			getModel().getBorrow().setRePayAmount(getModel().getBorrow().getRePayAmount() + getModel().getAmount());
			getManager().getDao().save(getModel().getBorrow());
		}
		return "cashierAudit";
	}
	
	/**
	 * 查看还款信息
	 * @return
	 */
	public String view() {
		return VIEW;
	}
	
	// 获得关联部门
	private Dept getLoginUserDept() {
		User user = UserUtil.getLoginUser(getRequest());
		user = getManager().getDao().get(User.class, user.getId());
		Dept dept = user.getDept();
		if (dept == null) {
			throw new ApplicationException("无关联部门");
		}
		return dept;
	}
	
	/**
	 * 还款类型常量
	 */
	public Map<String, String> getRePayTypeMap() {
		return RePayConstants.REPAY_TYPE_MAP;
	}
	
	/**
	 * 显示审批状态
	 */
	public Map<String, String> getAuditStatusMap() {
		return FlowConstants.AUDIT_STATUS_MAP;
	}

	/**
	 * 审批是否通过
	 */
	public Map<String, String> getStatusMap() {
		return FlowConstants.STATUS_MAP;
	}
	
	/**
	 * return
	 */
	public Map<String, String> getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(Map<String, String> jsonResult) {
		this.jsonResult = jsonResult;
	}
	
	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

}
